package cn.wolfcode.shop.cloud.filter;

import cn.wolfcode.shop.cloud.Result;
import cn.wolfcode.shop.cloud.member.feign.MemberFeignApi;
import cn.wolfcode.shop.cloud.util.CookieUtil;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class CookieRefreshFilter extends ZuulFilter {

    @Autowired
    MemberFeignApi memberFeignApi;

    /**
     * filter的类型
     * @return
     */
    @Override
    public String filterType() {
        return FilterConstants.POST_TYPE;
    }

    /**
     * filter的优先级
     * @return
     */
    @Override
    public int filterOrder() {
        return 0;
    }

    /**
     * 判断哪些需要进行过滤
     * 返回true就进入到run方法里面进行过滤操作
     * @return
     */
    @Override
    public boolean shouldFilter() {
        //判断请求中是否携带者cookie name = userToken
        RequestContext ctx = RequestContext.getCurrentContext();
        HttpServletRequest request = ctx.getRequest();
        String token = CookieUtil.getCookieValue(request,"userToken");
        if(!StringUtils.isEmpty(token)){
            return true;
        }
        return false;
        //return ctx.getThrowable() != null && !ctx.getBoolean("sendErrorFilter.ran", false);
    }

    @Override
    public Object run() {
        RequestContext ctx = RequestContext.getCurrentContext();
        HttpServletResponse response = ctx.getResponse();
        HttpServletRequest request = ctx.getRequest();
        response.setContentType("text/json;charset=utf8");
        //如果用户30分钟有操作,延迟cookie过期时间
        //延迟redis过期时间,用户服务里操作
        //远程调用会员服务
        String token = CookieUtil.getCookieValue(request,"userToken");
        Result<Boolean> result = memberFeignApi.refreshTime(token);
        //延长cookie的过期时间
        if(result != null && result.getCode() == 200 && result.getData()){
            CookieUtil.addCookie("userToken",token,1800,response);
        }
        ctx.setSendZuulResponse(false);
        return null;
    }
}
